package com.runnirr.doodles.AsyncOperations;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.runnirr.doodles.DoodleList;
import com.runnirr.doodles.Database.DataManagementHelper;
import com.runnirr.doodles.Helpers.DoodleData;

import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

public class LoadDoodlesAsync extends AsyncTask<DoodleList, Integer, List<DoodleData>> {

	private List<DoodleData> doodleList = new LinkedList<DoodleData>();
	private DoodleList dv;
	private int year;
	private int month;
	
	@Override
	protected List<DoodleData> doInBackground(DoodleList... params) {
		dv = params[0];
		Intent intent = dv.getIntent();
		year = intent.getIntExtra("year", Calendar.YEAR);
		month = intent.getIntExtra("month", Calendar.MONTH);
		
		DataManagementHelper dbHelper = new DataManagementHelper(dv);	
		this.doodleList = dbHelper.selectDoodlesFromStorage(year, month);
		int count = this.doodleList.size();
		System.out.println("Count from db: " + count);
		if (this.doodleList.size() > 0){
			Log.i("Loading Doodles", "Loading doodles from local storage");
	  		return this.doodleList;
		}
		Log.i("Fetching Doodles", "Fetching doodles from the internet");
				
		
		JSONArray doodleItems = getDoodleJsonArray();
		if (doodleItems == null){
			return this.doodleList;
		}
		
		createDoodleItems(doodleItems);
		System.out.println("Number of doodles: " + doodleList.size());
		return this.doodleList;
	}
	
	@Override
    protected void onPostExecute(List<DoodleData> result) {
		dv.onLoadDoodlesComplete(result);
    }

	
	private JSONArray getDoodleJsonArray(){
		String url = "http://www.google.com/doodles/json/" + year + "/" + month;
		JSONArray doodleJsonArray = null;
		
		try {
		    URL gDoodle = new URL(url);
		    URLConnection doodleCon = gDoodle.openConnection();
		    BufferedReader in = new BufferedReader(new InputStreamReader(doodleCon.getInputStream()));
		    String line;
		    String strData = "";
		    while ((line = in.readLine()) != null) {   
		        strData += line;
		    }
		    doodleJsonArray = new JSONArray(strData);
		}catch(Exception e){
			// TODO: Too lazy to do this
		}
		return doodleJsonArray;
	}
	
	private void createDoodleItems(JSONArray doodleItems){		
		for (int i = 0; i < doodleItems.length(); i++){
			JSONObject jo = null;
			DoodleData dd = null;
			try {
				jo = doodleItems.getJSONObject(i);
				dd = getDoodleData(jo);
			} catch (JSONException e) {
				Log.e("CreateDoodleItems Exception", e.getLocalizedMessage());
			}
			if(dd != null){
				this.doodleList.add(0, dd);
			}else{
				Log.e("CreateDoodleItems", "Error getting Doodle data");
			}
		}
	}
	
	private DoodleData getDoodleData(JSONObject doodleObject) throws JSONException{
		DoodleData dd = new DoodleData(
				year,
				month,
				doodleObject.getString("name"), 
				doodleObject.getString("title"),
				doodleObject.getString("blog_text"),
				doodleObject.getString("url"),
				doodleObject.getLong("run_date") * 1000, // Stored in seconds, convert to milliseconds
				doodleObject.getString("id"));	
		try{
			new DataManagementHelper(dv).insertDoodleToStorage(dd);			
		} catch(Exception e){
			Log.e("Database Write Error", "Could not write " + dd.title + " to the database");
		} 
		return dd;
	}
	

}
